import { IAppOption } from "../typings"
import { getOpenId } from "./utils/api"

// app.ts
App<IAppOption>({
    globalData: {
        environmentName: '',
        forceEnvironment: false,
        forceEnvironmentName: '',
        version: '0.0.1',
        envTag: '',
        environment: {
            api_domain: '',
            openid: null,
            userInfo: null,
            localUserInfo: null,
            token: "",
            tokenExpTime: 0
        },
        local: {
            api_domain: 'http://127.0.0.1:8111',
            openid: null,
            userInfo: null,
            localUserInfo: null,
            token: "",
            tokenExpTime: 0
        },
        dev: {
            api_domain: 'https://xc.1088web.com',
            openid: null,
            userInfo: null,
            localUserInfo: null,
            token: "",
            tokenExpTime: 0
        },
        prod: {
            api_domain: 'https://www.cmxczx.net',
            openid: null,
            userInfo: null,
            localUserInfo: null,
            token: "",
            tokenExpTime: 0
        },
    },
    onLaunch() {
        // 获取当前系统环境来设置版本
        let accountInfo = wx.getAccountInfoSync()
        if (this.globalData.forceEnvironment == false && accountInfo.miniProgram.envVersion == "release") {
            this.globalData.environment = this.globalData.prod
            this.globalData.envTag = '正式版'
            this.globalData.environmentName = "prod"
        } else if (this.globalData.forceEnvironment == false && accountInfo.miniProgram.envVersion == "trial") {
            this.globalData.environment = this.globalData.dev
            this.globalData.envTag = '体验版'
            this.globalData.environmentName = "dev"
        } else if (this.globalData.forceEnvironment == false && accountInfo.miniProgram.envVersion == "develop") {
            this.globalData.environment = this.globalData.dev
            this.globalData.envTag = '开发版'
            this.globalData.environmentName = "dev"
        }
        // 如果是开发者工具并且是develop环境则切换到本地开发环境
        let systemInfo = wx.getSystemInfo()
        let that = this;
        systemInfo.then(function (data) {
            if (that.globalData.forceEnvironment == false && accountInfo.miniProgram.envVersion == 'develop' && data.platform == 'devtools') {
                that.globalData.environment = that.globalData.local
                that.globalData.envTag = '本地版'
                that.globalData.environmentName = "local"
            }
        })
        // 判断是否开启了强制环境，如果是强制环境则切换到指定强制的环境
        if (this.globalData.forceEnvironment == true) {
            switch (this.globalData.forceEnvironmentName) {
                case "local":
                    this.globalData.environment = that.globalData.local
                    this.globalData.envTag = '本地版'
                    this.globalData.environmentName = "local"
                    break
                case "dev":
                    this.globalData.environment = this.globalData.dev
                    this.globalData.envTag = '体验版'
                    this.globalData.environmentName = "dev"
                    break
                case "trial":
                    this.globalData.environment = this.globalData.dev
                    this.globalData.envTag = '体验版'
                    this.globalData.environmentName = "dev"
                    break
                case "prod":
                    this.globalData.environment = this.globalData.prod
                    this.globalData.envTag = '正式版'
                    this.globalData.environmentName = "prod"
                    break
            }
        }

        // 展示本地存储能力
        const logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

        // 登录
        this.getUserInfo();
        // 从缓存获取数据自动登录，因为本地环境判断的问题，需要等本地环境判断完毕才执行获取内存，否则会覆盖
        systemInfo.then((_data) => {
            this.getStorageDataAuthLogin();
        })
    },
    // 从缓存获取数据自动登录
    getStorageDataAuthLogin() {
      let userInfo = wx.getStorageSync("userInfo");
      let token = wx.getStorageSync("token");
      let tokenExpTime = wx.getStorageSync("tokenExpTime");
      var newDateTime = Date.parse(new Date().toString());
      var now = newDateTime / 1000;
      if (userInfo && token && tokenExpTime && now < tokenExpTime) {
        this.globalData.environment!.userInfo = userInfo
        this.globalData.environment!.token = token
        this.globalData.environment!.tokenExpTime = tokenExpTime
        // 如果用户没有填账号，则提示去填写账号
        if(! userInfo.username) {
            wx.reLaunch({
                url: "/pages/user/register/index"
            })
        }
      } 
    },
    // 获取userInfo
    getUserInfo() {
        let openid = wx.getStorageSync("openid");
        let promiseObj = new Promise(function (resolve, reject) {
            if(! openid){
                wx.login({
                    success (res) {
                        let promise = getOpenId({code: res.code})
                        promise.then((response:any) => {
                            // that.globalData.environment!.userInfo = response.userinfo
                            wx.setStorageSync("openid", response.openid)
                            resolve(response.openid)
                        }).catch((_e:Error) => {
                            reject("获取code失败")
                        })                        
                    },
                    fail (_e) {
                        reject("获取code失败")
                    }
                })
            } else {
                resolve(openid)
            }
        })

        promiseObj.then((openid: any) => {
            this.globalData.environment!.openid = openid
        }).catch((_e) => {
            // console.log(_e)
        })
    },
    // 验证登录的方法
    checkLogined() {
        if (!this.globalData.environment?.userInfo) {
            wx.showModal({
                title: '温馨提示',
                content: '需要您去登录哦`',
                cancelText:'再逛会',
                confirmText:'去登录',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: "/pages/login/auth/index"
                        })
                    } else if (res.cancel) {
                        // console.log('用户点击取消')
                    }
                }
            })
        }
    },
    // 去登录的方法
    redirectLogin(redirectUrl: string| null | undefined) {
        if(redirectUrl) {
            wx.navigateTo({ url: "/pages/login/auth/index?redirectUrl=" + redirectUrl })
        } else {
            wx.navigateTo({ url: "/pages/login/auth/index" })
        }
    }
})